package com.work.yshop.ui.fragment;

import android.content.Intent;
import android.graphics.Typeface;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.TextView;
import android.widget.Toast;

import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.fragment.app.Fragment;
import androidx.recyclerview.widget.RecyclerView;
import androidx.recyclerview.widget.StaggeredGridLayoutManager;

import com.work.yshop.R;
import com.work.yshop.adapter.ProductWaterfallAdapter;
import com.work.yshop.databinding.FragmentHomeBinding;
import com.work.yshop.model.Product;
import com.work.yshop.mvp.contract.HomeContract;
import com.work.yshop.mvp.presenter.HomePresenter;
import com.work.yshop.ui.activity.ProductDetailActivity;
import com.work.yshop.ui.activity.SearchResultsActivity;

import java.util.ArrayList;
import java.util.List;

/**
 * 首页Fragment
 */
public class HomeFragment extends Fragment implements HomeContract.View {

    private FragmentHomeBinding binding;
    private ProductWaterfallAdapter productAdapter;
    private List<TextView> categoryTabs;
    private HomeContract.Presenter presenter;
    private boolean isLoading = false;

    public static HomeFragment newInstance() {
        return new HomeFragment();
    }

    @Nullable
    @Override
    public View onCreateView(@NonNull LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
        binding = FragmentHomeBinding.inflate(inflater, container, false);
        return binding.getRoot();
    }

    @Override
    public void onViewCreated(@NonNull View view, @Nullable Bundle savedInstanceState) {
        super.onViewCreated(view, savedInstanceState);
        
        // 初始化Presenter
        presenter = new HomePresenter(requireContext());
        ((HomePresenter) presenter).attachView(this);
        
        // 初始化UI
        initViews();
        // 设置监听器
        setupListeners();
        // 加载推荐商品数据
        presenter.getRecommendProducts();
    }

    private void initViews() {
        // 初始化分类Tab
        categoryTabs = new ArrayList<>();
        categoryTabs.add(binding.categoryRecommend);
        categoryTabs.add(binding.categoryFruits);
        categoryTabs.add(binding.categoryGrain);
        categoryTabs.add(binding.categoryTools);
        categoryTabs.add(binding.categorySpecial);
        categoryTabs.add(binding.categoryLivestock);

        // 设置默认选中的分类Tab
        setSelectedCategoryTab(0);

        // 设置分类点击监听
        for (int i = 0; i < categoryTabs.size(); i++) {
            final int position = i;
            categoryTabs.get(i).setOnClickListener(v -> setSelectedCategoryTab(position));
        }
        
        // 初始化商品列表 - 使用瀑布流布局
        StaggeredGridLayoutManager layoutManager = new StaggeredGridLayoutManager(2, StaggeredGridLayoutManager.VERTICAL);
        binding.recyclerProducts.setLayoutManager(layoutManager);
        productAdapter = new ProductWaterfallAdapter();
        binding.recyclerProducts.setAdapter(productAdapter);
    }

    private void setupListeners() {
        // 设置商品点击监听器
        productAdapter.setOnItemClickListener(position -> {
            // 获取当前点击的商品
            Product product = productAdapter.getItem(position);
            if (product != null) {
            // 跳转到商品详情页
                ProductDetailActivity.start(requireContext(), product.getId());
            }
        });

        // 设置搜索框点击事件
        binding.searchView.setOnClickListener(v -> {
            // 使用静态方法启动搜索结果页面
            SearchResultsActivity.start(requireContext(), null);
        });
        
        // 设置滚动监听，实现上拉加载更多
        binding.recyclerProducts.addOnScrollListener(new RecyclerView.OnScrollListener() {
            @Override
            public void onScrollStateChanged(@NonNull RecyclerView recyclerView, int newState) {
                super.onScrollStateChanged(recyclerView, newState);
                
                // 检查是否滑动到底部
                if (!recyclerView.canScrollVertically(1) && !isLoading) {
                    presenter.loadMoreProducts();
                }
            }
        });
        
        // 设置下拉刷新
        binding.swipeRefresh.setColorSchemeResources(R.color.green_500);
        binding.swipeRefresh.setOnRefreshListener(() -> {
            // 刷新当前分类的数据
            presenter.getProductsByCategory(getCategoryPosition());
        });
    }

    /**
     * 设置选中的分类Tab
     */
    private void setSelectedCategoryTab(int position) {
        for (int i = 0; i < categoryTabs.size(); i++) {
            TextView tab = categoryTabs.get(i);
            if (i == position) {
                // 选中状态：绿色 + 粗体
                tab.setTextColor(getResources().getColor(R.color.green_500));
                tab.setTypeface(null, Typeface.BOLD);
            } else {
                // 未选中状态：灰色 + 正常字体
                tab.setTextColor(getResources().getColor(R.color.text_secondary));
                tab.setTypeface(null, Typeface.NORMAL);
            }
        }

        // 根据分类筛选数据
        presenter.getProductsByCategory(position);
    }

    /**
     * 获取当前选中的分类位置
     */
    private int getCategoryPosition() {
        for (int i = 0; i < categoryTabs.size(); i++) {
            if (categoryTabs.get(i).getCurrentTextColor() == getResources().getColor(R.color.green_500)) {
                return i;
            }
        }
        return 0;
    }

    @Override
    public void showLoading() {
        isLoading = true;
        binding.swipeRefresh.setRefreshing(true);
    }

    @Override
    public void hideLoading() {
        isLoading = false;
        binding.swipeRefresh.setRefreshing(false);
    }

    @Override
    public void showProducts(List<Product> products) {
        productAdapter.setData(products);
    }

    @Override
    public void showEmpty() {
        // 显示空状态
        Toast.makeText(requireContext(), "暂无商品数据", Toast.LENGTH_SHORT).show();
    }

    @Override
    public void showError(String message) {
        Toast.makeText(requireContext(), message, Toast.LENGTH_SHORT).show();
    }

    @Override
    public void onDestroyView() {
        super.onDestroyView();
        if (presenter != null) {
            presenter.detachView();
        }
        binding = null;
    }
} 